"""系统健康检查 - 验证所有组件正常运行"""
import subprocess
import sys
import time

print("="*70)
print(" SYSTEM HEALTH CHECK")
print("="*70)

all_good = True

# 1. 检查后端服务
print("\n[1/4] Checking backend service...")
result = subprocess.run(
    'netstat -ano | findstr :8000 | findstr LISTENING',
    shell=True,
    capture_output=True,
    text=True
)
if result.stdout.strip():
    print("  [PASS] Backend is running on port 8000")
else:
    print("  [FAIL] Backend is not running")
    all_good = False

# 2. 检查dashscope库
print("\n[2/4] Checking dashscope library...")
result = subprocess.run(
    'backend\\venv\\Scripts\\python.exe -c "import dashscope; print(\'OK\')"',
    shell=True,
    capture_output=True,
    text=True
)
if 'OK' in result.stdout:
    print("  [PASS] Dashscope is installed in backend/venv")
else:
    print("  [FAIL] Dashscope not available")
    print(f"  Error: {result.stderr}")
    all_good = False

# 3. 检查API响应
print("\n[3/4] Checking API health...")
result = subprocess.run(
    'curl -s http://127.0.0.1:8000/docs',
    shell=True,
    capture_output=True,
    text=True,
    timeout=5
)
if 'swagger' in result.stdout.lower() or 'openapi' in result.stdout.lower():
    print("  [PASS] API is responding")
else:
    print("  [WARN] API may not be fully ready")

# 4. 检查日志中的错误
print("\n[4/4] Checking for errors in logs...")
try:
    with open('server.log', 'r', encoding='utf-8') as f:
        log_content = f.read()

    if 'dashscope library not installed' in log_content.lower():
        # 检查是否是旧的错误（在最近的启动之前）
        recent_logs = log_content.split('Application startup complete')[-1]
        if 'dashscope library not installed' in recent_logs.lower():
            print("  [FAIL] Dashscope errors detected in recent logs")
            all_good = False
        else:
            print("  [PASS] No recent dashscope errors")
    else:
        print("  [PASS] No dashscope errors in logs")

    if 'error' in log_content.lower().split('application startup complete')[-1]:
        print("  [WARN] Some errors detected in recent logs")
except Exception as e:
    print(f"  [WARN] Could not read logs: {e}")

# 总结
print("\n" + "="*70)
if all_good:
    print(" [SUCCESS] SYSTEM IS HEALTHY AND READY!")
    print("="*70)
    print("\nYou can now access:")
    print("  Frontend: http://127.0.0.1:5173")
    print("  Backend API: http://127.0.0.1:8000")
    print("  API Docs: http://127.0.0.1:8000/docs")
    print("\nAI Engine Status: ACTIVE (DashScope/Qwen3)")
    sys.exit(0)
else:
    print(" [ERROR] SYSTEM HAS ISSUES - See details above")
    print("="*70)
    sys.exit(1)
